using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;
using System.IO.Compression;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 数据清理服务
    /// </summary>
    public class DataCleanupService
    {
        private readonly IDataStorageService _dataStorage;
        private readonly ILogger<DataCleanupService> _logger;
        private readonly string _backupDirectory;

        public DataCleanupService(IDataStorageService dataStorage, ILogger<DataCleanupService> logger)
        {
            _dataStorage = dataStorage;
            _logger = logger;
            _backupDirectory = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                "DocumentCreationSystem", 
                "Backups"
            );
            Directory.CreateDirectory(_backupDirectory);
        }

        /// <summary>
        /// 执行完整的数据清理
        /// </summary>
        public async Task<DataCleanupResult> PerformFullCleanupAsync(DataCleanupOptions? options = null)
        {
            options ??= new DataCleanupOptions();
            
            try
            {
                _logger.LogInformation("开始执行完整数据清理...");

                // 创建备份
                DataBackupInfo? backup = null;
                if (options.CreateBackup)
                {
                    backup = await CreateBackupAsync("清理前自动备份");
                    if (backup == null)
                    {
                        _logger.LogWarning("备份创建失败，继续执行清理操作");
                    }
                    else
                    {
                        _logger.LogInformation($"备份已创建: {backup.BackupPath}");
                    }
                }

                // 执行数据清理
                var result = await _dataStorage.CleanupInvalidProjectReferencesAsync();
                
                if (backup != null)
                {
                    result.Message += $" (备份: {backup.BackupPath})";
                }

                _logger.LogInformation($"数据清理完成: {result.Message}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行数据清理时发生错误");
                return new DataCleanupResult
                {
                    IsSuccess = false,
                    Message = $"清理失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 创建数据备份
        /// </summary>
        public async Task<DataBackupInfo?> CreateBackupAsync(string description = "")
        {
            try
            {
                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                var backupFileName = $"data_backup_{timestamp}.zip";
                var backupPath = Path.Combine(_backupDirectory, backupFileName);

                _logger.LogInformation($"创建数据备份: {backupPath}");

                var dataDirectory = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                    "DocumentCreationSystem"
                );

                using (var archive = ZipFile.Open(backupPath, ZipArchiveMode.Create))
                {
                    // 备份所有JSON数据文件
                    var dataFiles = new[]
                    {
                        "projects.json",
                        "documents.json", 
                        "novel_projects.json",
                        "chapters.json",
                        "characters.json",
                        "vector_records.json",
                        "ai_model_configs.json",
                        "world_settings.json"
                    };

                    foreach (var fileName in dataFiles)
                    {
                        var filePath = Path.Combine(dataDirectory, fileName);
                        if (File.Exists(filePath))
                        {
                            archive.CreateEntryFromFile(filePath, fileName);
                        }
                    }

                    // 添加备份信息文件
                    var backupInfo = new
                    {
                        CreatedAt = DateTime.Now,
                        Description = description,
                        Version = "1.0",
                        Files = dataFiles.Where(f => File.Exists(Path.Combine(dataDirectory, f))).ToArray()
                    };

                    var infoEntry = archive.CreateEntry("backup_info.json");
                    using var infoStream = infoEntry.Open();
                    var infoJson = JsonConvert.SerializeObject(backupInfo, Formatting.Indented);
                    await infoStream.WriteAsync(System.Text.Encoding.UTF8.GetBytes(infoJson));
                }

                var fileInfo = new FileInfo(backupPath);
                var backup = new DataBackupInfo
                {
                    BackupPath = backupPath,
                    CreatedAt = DateTime.Now,
                    BackupSize = fileInfo.Length,
                    Description = description,
                    IsValid = true
                };

                _logger.LogInformation($"备份创建成功: {backupPath} ({fileInfo.Length} bytes)");
                return backup;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建数据备份失败");
                return null;
            }
        }

        /// <summary>
        /// 获取数据完整性报告
        /// </summary>
        public async Task<DataIntegrityReport> GetDataIntegrityReportAsync()
        {
            try
            {
                _logger.LogInformation("生成数据完整性报告...");
                var report = await _dataStorage.ValidateDataIntegrityAsync();
                _logger.LogInformation($"数据完整性报告生成完成，发现 {report.TotalIssuesCount} 个问题");
                return report;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成数据完整性报告失败");
                return new DataIntegrityReport
                {
                    IsValid = false,
                    ErrorMessage = ex.Message,
                    GeneratedAt = DateTime.Now
                };
            }
        }

        /// <summary>
        /// 清理旧备份文件
        /// </summary>
        public async Task<int> CleanupOldBackupsAsync(int keepDays = 30)
        {
            try
            {
                _logger.LogInformation($"清理 {keepDays} 天前的备份文件...");
                
                var cutoffDate = DateTime.Now.AddDays(-keepDays);
                var backupFiles = Directory.GetFiles(_backupDirectory, "data_backup_*.zip");
                var deletedCount = 0;

                foreach (var backupFile in backupFiles)
                {
                    var fileInfo = new FileInfo(backupFile);
                    if (fileInfo.CreationTime < cutoffDate)
                    {
                        try
                        {
                            File.Delete(backupFile);
                            deletedCount++;
                            _logger.LogInformation($"删除旧备份: {Path.GetFileName(backupFile)}");
                        }
                        catch (Exception ex)
                        {
                            _logger.LogWarning(ex, $"删除备份文件失败: {backupFile}");
                        }
                    }
                }

                _logger.LogInformation($"清理完成，删除了 {deletedCount} 个旧备份文件");
                return deletedCount;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理旧备份文件失败");
                return 0;
            }
        }

        /// <summary>
        /// 获取所有备份信息
        /// </summary>
        public async Task<List<DataBackupInfo>> GetBackupListAsync()
        {
            try
            {
                var backups = new List<DataBackupInfo>();
                var backupFiles = Directory.GetFiles(_backupDirectory, "data_backup_*.zip");

                foreach (var backupFile in backupFiles)
                {
                    var fileInfo = new FileInfo(backupFile);
                    var backup = new DataBackupInfo
                    {
                        BackupPath = backupFile,
                        CreatedAt = fileInfo.CreationTime,
                        BackupSize = fileInfo.Length,
                        Description = "数据备份",
                        IsValid = await ValidateBackupAsync(backupFile)
                    };
                    backups.Add(backup);
                }

                return backups.OrderByDescending(b => b.CreatedAt).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取备份列表失败");
                return new List<DataBackupInfo>();
            }
        }

        /// <summary>
        /// 验证备份文件有效性
        /// </summary>
        private async Task<bool> ValidateBackupAsync(string backupPath)
        {
            try
            {
                using var archive = ZipFile.OpenRead(backupPath);
                return archive.Entries.Any(e => e.Name.EndsWith(".json"));
            }
            catch
            {
                return false;
            }
        }
    }
}
